﻿using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using MySqlConnector;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Unicode;
using System.Threading.Tasks;

namespace _04.Net8Cache.Customs
{
    public class CustomCacheMySQL : IDistributedCache
    {
        /// <summary>
        /// 缓存自定义-MySQL缓存
        /// </summary>
        public CustomCacheOptions _CustomCacheOptions { get; set; }
        public CustomCacheMySQL(CustomCacheOptions customCacheOptions)
        {
            _CustomCacheOptions = customCacheOptions;
        }

        public byte[]? Get(string key)
        {
            //_Cache.TryGetValue(key, out var value);
            return null;
        }

        public async Task<byte[]> GetAsync(string key, CancellationToken token = default)
        {
            // 异步操作通常用于访问外部资源，但在这个内存缓存示例中，我们可以直接返回结果
            return Get(key);
        }

        public void Refresh(string key)
        {
            // 在内存缓存中，刷新操作可能不需要执行任何操作
        }

        public async Task RefreshAsync(string key, CancellationToken token = default)
        {
            // 异步操作通常用于访问外部资源，但在这个内存缓存示例中，我们可以直接返回
            Refresh(key);
        }

        public void Remove(string key)
        {
            //_Cache.TryRemove(key, out _);
        }

        public async Task RemoveAsync(string key, CancellationToken token = default)
        {
            Remove(key);
        }

        public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
        {
            using (var connection = new MySqlConnection(_CustomCacheOptions._connectionString))
            {
                var command = connection.CreateCommand();
                command.CommandText = "INSERT INTO cache (Cachekey, CacheValue) VALUES (@Cachekey, @CacheValue)";
                command.Parameters.AddWithValue("@Cachekey", key);
                command.Parameters.AddWithValue("@CacheValue", Encoding.UTF8.GetString(value));

                connection.Open();
                command.ExecuteNonQuery();
            }
        }

        public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default)
        {
            Set(key, value, options);
        }

    }
}
